    //
//  WhereViewController.m
//  SpendFunk
//
//  Created by dongmh on 5/6/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "WhereViewController.h"
#import "image.h"
#import "SpendFunkAppDelegate.h"
#import "Post1ViewController.h"
#import "Global.h"
@implementation WhereViewController


 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)init{
	searching = NO;
    return self;
}



// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	[super loadView];
	[self initView];
}
- (void)initView{
	
	NSString *path = [[NSString alloc] initWithFormat:@"%@",IMG_HEADER];
	UIImage *img = [UIImage imageNamed:path];
	UIImageView *imgvBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0 -20, img.size.width, img.size.height)];
	[imgvBar setImage:img];
	[self.view addSubview:imgvBar];
	[imgvBar setUserInteractionEnabled:YES];
	[imgvBar release];
	
	//back button
	[path release];
	//[img release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BTN_BACK];
	img = [UIImage imageNamed:path];
	m_pBtnBack = [[UIButton alloc] initWithFrame:CGRectMake(5, 5 -20, img.size.width, img.size.height)];
	[m_pBtnBack setBackgroundImage:img forState:UIControlStateNormal];
	[m_pBtnBack setTitle:@"Back" forState:UIControlStateNormal];
	[m_pBtnBack setBackgroundColor:[UIColor clearColor]];
	m_pBtnBack.titleLabel.textColor = [UIColor whiteColor];
	[m_pBtnBack addTarget:nil action:@selector(onBackClick) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:m_pBtnBack];
	
	// Background for it
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BKGR_VIEW];
	img = [UIImage imageNamed:path];
	UIImageView *imgvBkgr = [[UIImageView alloc] initWithFrame:CGRectMake(0, 45 -20, img.size.width, img.size.height)];
	[imgvBkgr setImage:img];
	[self.view addSubview:imgvBkgr];
	[imgvBkgr setUserInteractionEnabled:YES];
	[imgvBkgr release];	
	
	// Searbar
	
	m_pSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 5, 320, 30)];
	[m_pSearchBar setBackgroundColor:[UIColor clearColor]];
	m_pSearchBar.autocorrectionType = UITextAutocorrectionTypeYes;
	m_pSearchBar.delegate = self;
	[imgvBkgr addSubview:m_pSearchBar];
	m_pSearchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	searching = NO;
	letUserSelectRow = YES;
	rowCheckedWh = NO;
	// Table view for places
	
	m_pTblePlaces = [[UITableView alloc] initWithFrame:CGRectMake(10, 40, 300, 280) style:UITableViewStyleGrouped];
	[m_pTblePlaces setBackgroundColor:[UIColor clearColor]];
	m_pTblePlaces.scrollEnabled = YES; 
	[imgvBkgr addSubview:m_pTblePlaces];
	m_pTblePlaces.delegate = self;
	m_pTblePlaces.dataSource = self;
	
	// Insert item into array of place items
	//m_pArrPlaceItems = [[NSMutableArray  arrayWithObjects:@"Ha noi - Viet Nam",@"Ha noi - Viet Nam",@"Ha noi - Viet Nam",@"Ha noi - Viet Nam",@"Ha noi - Viet Nam",@"Ha noi - Viet Nam",@"Ha noi - Viet Nam",@"Ha noi - Viet Nam",nil] retain];
	copyListOfItems = [[NSMutableArray arrayWithCapacity:0] retain];// Coutn of nearby places
	countPlaces = [m_pArrPlaceItems count] +1;
}
#pragma mark setArrPlaces
- (void)setArrPlaces:(NSArray*)arrPlaces{
	if (m_pArrPlaceItems) {
		[m_pArrPlaceItems release];
		m_pArrPlaceItems = nil;
	}
	m_pArrPlaceItems = [arrPlaces retain];
	[m_pTblePlaces reloadData];
}
- (void)onBackClick{
	[m_pSearchBar resignFirstResponder];
	[g_AppDelegate backToPost1];
}
#pragma mark -
#pragma mark UISearchBarDelegate
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {
	
	searching = YES;
	letUserSelectRow = NO;
	m_pTblePlaces.scrollEnabled = NO;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar;{
	[searchBar resignFirstResponder];
	[m_pTblePlaces reloadData];
}
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
	
	//Remove all objects first.
	[copyListOfItems removeAllObjects];
	
	if([searchText length] >0) {
		
		searching = YES;
		letUserSelectRow = YES;
		m_pTblePlaces.scrollEnabled = YES;
		[self searchTableView];
	}
	else {
		
		searching = NO;
		letUserSelectRow = NO;
		m_pTblePlaces.scrollEnabled = NO;
	}
	
	[m_pTblePlaces reloadData];
}
//- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
//	
//	[self searchTableView];
//}

- (void) searchTableView {
	
	NSString *searchText = m_pSearchBar.text;
	NSMutableArray *venue = (NSMutableArray*)m_pArrPlaceItems;
	
	//NSString *name		= [venue objectForKey:@"name"];
	for (NSString *sTemp in [venue valueForKey:@"name"])
	{
		NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
		if (titleResultsRange.length >0)
			[copyListOfItems addObject:sTemp];
	}
	
	
}
#pragma mark -
#pragma mark UITableViewDelegate

UITableViewCell	*cellChecked;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
	if (!searching) {
		[m_pSearchBar resignFirstResponder];
	}
	if (indexPath.row == countPlaces -1) {
		// Load more places
		return;
	} else {
		if (!rowCheckedWh) {
			[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
			cellChecked = [tableView cellForRowAtIndexPath:[tableView indexPathForCell:cell]];
			rowCheckedWh = YES;
		} else {
			[cellChecked setAccessoryType:UITableViewCellAccessoryNone];
			[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
			cellChecked = [tableView cellForRowAtIndexPath:[tableView indexPathForCell:cell]];
		}
	}
	NSDictionary *venue = (NSDictionary*)[m_pArrPlaceItems objectAtIndex:indexPath.row];
	
	NSString *namePlaces		= [venue objectForKey:@"name"];
	if (!SpendInfo) {
		SpendInfo  = [[NSMutableDictionary alloc] init];
		[SpendInfo retain];
	}
	[SpendInfo setObject:namePlaces forKey:@"kPlace"];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	return 50;
}

#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
	//return countPlaces;
	if (searching)
		return [copyListOfItems count];
	else {
		
		return countPlaces;
	}
	
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	static NSString *CellIdentifier = @"Cell";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
	}
	if(searching)
		cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
	else {
	
				if (indexPath.row == (countPlaces -1)) {
						cell.textLabel.text = @"More Nearby Place...";
				}else	{
					//cell.textLabel.text = [m_pArrPlaceItems objectAtIndex:indexPath.row];
					//Get dictionary with venue information
					NSDictionary *venue = (NSDictionary*)[m_pArrPlaceItems objectAtIndex:indexPath.row];
					
					NSString *name		= [venue objectForKey:@"name"];
					NSNumber *distance	= [venue objectForKey:@"distance"];
					
					cell.textLabel.text = name;
					cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ meters", distance];
					//NSLog(@"%@",[[venue objectForKey:@"name"] valueForKey:@"iconurl"]);
					NSLog(@"%@",[venue objectForKey:@"address"]);
			}
	}
	[cell setAccessoryType:UITableViewCellAccessoryNone];
	return cell;
}
#pragma mark Event touch screen
-(void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event
{
	NSLog(@"Touch begin");
	//UITouch *touch = [[event allTouches] anyObject];
	//CGPoint touchLocation = [touch locationInView:touch.view];  //=> toa do
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
	NSLog(@"Touch move");
}
- (void) touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
	NSLog(@"Touch end");
	[m_pSearchBar resignFirstResponder];
}

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
